package com.hack4jp.hackearthquakes;

import java.net.URL;
import java.util.ArrayList;
import java.util.Date;

import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.TwitterException;
import twitter4j.URLEntity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

public class TwitterTimelineActivity extends Activity {

	TwitterObject twt = null;	
	
	@Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        
		setContentView(R.layout.timeline);
	
		twt = new TwitterObject();		
		
		try {
			if (twt.tokenAvailable()) {
				viewTimeline();
			} else {
				Intent intent = new Intent(this, TwitterLogin.class);
				this.startActivityForResult(intent, 0);
			}		
		}catch(Exception e){
			DialogInterface.OnClickListener onOK = new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			};			
			
    		String strMsg = e.getMessage();
    		String strAlert = getString(R.string.alertcheckconnection);
    		showAlert(strAlert + "\n" + strMsg, null, onOK, null);		
		}
	}

	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
	{
		if(resultCode == RESULT_OK){
			try{
				viewTimeline();
			}catch(Exception e){
				Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
			}
		} else if(resultCode == RESULT_CANCELED){
			DialogInterface.OnClickListener onOK = new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			};			
			
			String msg = getString(R.string.autherror);
			showAlert(msg, null, onOK, null);
		}
	}	
	
	protected void viewTimeline() throws TwitterException
	{
		if (!twt.twitterAvailable()) {
			twt.createFactory();
		}		
		
		ResponseList<Status> res = twt.getTwitter().getHomeTimeline();
		ArrayList<TweetItem> items = new ArrayList<TweetItem>();
		for (Status status : res) {
	        String tweet = status.getText();
	        Date dt = status.getCreatedAt();
	        
	        if (tweet.indexOf(HackEarthquakes.HASHTAG) < 0)
	        	continue;
	        
			URL imageUrl = status.getUser().getProfileImageURL();
	        URLEntity[] urlArray = status.getURLEntities();
			for(int i = 0;i < urlArray.length;i++){
				try{
		        	URL urlImagePage = urlArray[i].getExpandedURL();
		        	if (urlImagePage.getHost().equals("twitpic.com")) {
		        		String thumbnailPath = "/show/thumb" + urlImagePage.getPath();
		        		imageUrl = new URL(urlImagePage.getProtocol(), urlImagePage.getHost(), thumbnailPath);
		        		break;
		        	}
				} catch(Exception e) {
		        }
		    }

	        items.add(new TweetItem(tweet, imageUrl, dt));
		}

		if (items.size() > 0){
			TwitterAdapter adapter = new TwitterAdapter(this, R.layout.tlrow, items);
			ListView list = (ListView)findViewById(R.id.list_tweets);
			list.setAdapter(adapter);
		} else {
			DialogInterface.OnClickListener onOK = new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			};

			String msg = getString(R.string.notweet);
			showAlert(msg, null, onOK, null);
		}
	}
	
	private void showAlert(String message, String caption,
			DialogInterface.OnClickListener onOK,
			DialogInterface.OnClickListener onCancel) {
		AlertDialog.Builder ab = new AlertDialog.Builder(this);

		if (caption != null)
			ab.setTitle(caption);

		ab.setMessage(message);

		ab.setPositiveButton("OK", onOK);

		if (onCancel != null) {
			ab.setNegativeButton("Cancel", onCancel);
		}

		AlertDialog alertDialog = ab.create();
		alertDialog.show();
	}
}
